﻿using XjjXmm.Infrastructure.Constant;
using xjjxmm.infrastructure.Webs;

namespace XjjXmm.Infrastructure.User;

public class UserContextAccessor : IUserContextAccessor
{
	private readonly ThreadLocalContext _threadLocalContext;

	public UserContextAccessor(ThreadLocalContext threadLocalContext)
	{
		_threadLocalContext = threadLocalContext;
	}

	public UserContext UserContext
	{
		set => _threadLocalContext.Set(CacheKey.USER, value);
		get => _threadLocalContext.Get<UserContext>(CacheKey.USER)!;
	}
}


/*public class UserContext :  IUserContext
	{
		private readonly IHttpContextAccessor _accessor;

		//private readonly IEasyCachingProvider _cache;

		public UserContext(IHttpContextAccessor accessor)
		{
			_accessor = accessor;
		}

		
		public string Id => _accessor?.HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == ClaimTypes.NameIdentifier)?.Value??"";
		

		//return _accessor?.HttpContext?.User.Identity?.Name?.ToLong() ?? 0;
		//public bool IsAccess => _accessor?.HttpContext?.User.Claims?.FirstOrDefault(t => t.Type == "IsAccess")?.Value != "0";

		public string ClientId => _accessor?.HttpContext?.User.Claims?.FirstOrDefault(t => t.Type == "ClientId")?.Value ?? "";
		
	

		public string Token => _accessor?.HttpContext?.Request?.Headers["Authorization"].ToString()?.Replace("Bearer", "")?.Trim() ?? "";

		private UserCacheContext? _userCacheContext = null;

		private UserCacheContext UserCacheContext
		{
			get
			{
				try
				{
					_userCacheContext ??= RedisKit.GetInstance().HashGet<UserCacheContext>(CacheKey.User, Id);

					return _userCacheContext ?? new UserCacheContext();
				}
				catch
				{
					return new UserCacheContext();
				}
			}
		}
		
		public string LoginName => UserCacheContext.LoginName;

		public string NickName => UserCacheContext.NickName;
		
		
		public string TenantId => UserCacheContext.TenantId;
		
	}


public class UserCacheContext 
{
    public string LoginName { get; set; } = string.Empty;

    public string NickName { get; set; }  = string.Empty;

    public string TenantId { get; set; } = string.Empty;
}*/
